<?php
/**
 * Semester Date Controller
 * Semester Date   Management
 *
 * semester entry
 *
 * @version $Id: DateController.php 77 2010-04-25 07:28:48Z yingkuang.chen@gmail.com $
 * @license New BSD License
 * @uses Zend_Controller_Action
 * @package semester
 * @subpackage Controller
 */
class semester_DateController extends Zend_Controller_Action
{

    private $_weekData;

    function indexAction()
    {
        if ($this->_request->getParam('year')){
            $this->view->year =  $this->_request->getParam('year');
            $this->view->semester =  $this->_request->getParam('semester');
        }
        else {
            $this->view->year =  $this->view->Semester['year'];
            $this->view->semester =  $this->view->Semester['semester'];
        }


    }

    /**
     * 檢查本學期 semester_teacher 是否存在
     * @param $year
     * @param $semester
     * @return unknown_type
     */
    function _check_semester_teacher($year,$semester)
    {
        if ($semester == 2) {
            $pre_semester = 1;
            $pre_year = $year;
        }else {
            $pre_semester=2;
            $pre_year = $year-1;
        }
//        $db = Zend_Db_Table::getDefaultAdapter();
        $q = Doctrine_Query::create()
        ->select('COUNT(*) AS cc')
        ->from("Semester_Model_SemesterTeacher")
        ->where("year=?",$year)
        ->andWhere("semester=?",$semester);
        $res = $q->fetchOne(null,Doctrine_Core::HYDRATE_ARRAY);

        if ($res['cc']==0) {
            $q = Doctrine_Query::create()
            ->from("Semester_Model_SemesterTeacher")
            ->where("year=?",$pre_year)
            ->andWhere("semester=?",$pre_semester);
            $res = $q->fetchArray();

            foreach($res as $row){
                $row['year']	= $year;
                $row['semester'] = $semester;
                unset($row['sn']);
                $semesterTeacher = new Semester_Model_SemesterTeacher();
                $semesterTeacher->fromArray($row);
                $semesterTeacher->save();
//                $db->insert('semester_teacher',$row);
            }
        }
    }

    /**
     * 設定開學日
     * @return unknown_type
     */
    function setAction()
    {
        $form = new Semester_Form_Date();

        $this->view->year = (int)$this->_request->getParam('year');
        $this->view->semester = (int)$this->_request->getParam('semester');

        if ($this->_request->isPost() and $this->_request->getParam('save') and $this->view->year > 0 ){
            if ($form->isValid($this->_request->getParams())) {
                $semesterDuration = new Semester_Model_SemesterDuration();
                $q = Doctrine_Query::create()
                ->select('sn')
                ->from('Semester_Model_SemesterDuration')
                ->where('year=?',(int) $this->view->year)
                ->andWhere('semester=?',(int)$this->view->semester);
                $res = $q->fetchOne(null,Doctrine_Core::HYDRATE_ARRAY);
                $sn = $res['sn'];
                if ($res)
                $semesterDuration->assignIdentifier($sn);
                $semesterDuration->year = $this->_request->getParam('year');
                $semesterDuration->semester = $this->_request->getParam('semester');
                $semesterDuration->started_date = $this->_request->getParam('started_date');
                $semesterDuration->ended_date = $this->_request->getParam('ended_date');
                $semesterDuration->opened_date = $this->_request->getParam('opened_date');
                $semesterDuration->closed_date = $this->_request->getParam('closed_date');
                $semesterDuration->save();

                if (!$this->_request->getParam('week_setup') and $this->_request->getParam('year')) {
                    $q = Doctrine_Query::create()
                    ->delete('Semester_Model_SemesterWeek')
                    ->where('year=?',$this->_request->getParam('year'))
                    ->andWhere('semester=?',$this->_request->getParam('semester'));
                    $q->execute();
                }
                // 檢查 semester_teacher
                $this->_check_semester_teacher($this->view->year,$this->view->semester);
                $cache = Zend_Registry::get('cache');
                $cache->remove('semester'); // 重新 cache
                $this->_redirect('semester/date/index');
            }
        }

        $q = Doctrine_Query::create()
        ->from('Semester_Model_SemesterDuration')
        ->where('year=?',$this->view->year)
        ->andwhere('semester=?',$this->view->semester);
        $data = $q->fetchOne(null,Doctrine_Core::HYDRATE_ARRAY);
        if (!$data) {  // 預設日期
            $data['year'] = $this->view->year;
            $data['semester'] = $this->view->semester;
            if ($this->view->semester == 1) {
                $data['started_date'] = ($data['year']+1911).'-08-01';
                $data['ended_date'] = ($data['year']+1912).'-01-31';
                $data['opened_date'] = ($data['year']+1911).'-08-31';
                $data['closed_date'] = ($data['year']+1912).'-01-20';
            }
            else {
                $data['started_date'] = ($data['year']+1912).'-02-01';
                $data['ended_date'] = ($data['year']+1912).'-07-31';
                $data['opened_date'] = ($data['year']+1912).'-02-10';
                $data['closed_date'] = ($data['year']+1912).'-06-30';
            }
        }

        $this->view->weekData = Zend_Json::encode($this->_getWeekData($data));
        $this->view->weekSetupData = Zend_Json::encode($this->_getWeekSetupData($data));
       $form->setDefaults($data);
        $this->view->form = $form;
    }

    /**
     * 設定週次別
     *
     */
    function setweekAction()
    {
        $data =  $this->_request->getParam('data');
        $year= (int) $this->_request->getParam('year');
        $semester = (int) $this->_request->getParam('semester');

        $arr = explode(",",$data);
        $i =1;
        if ($arr) {
            $q = Doctrine_Query::create()
            ->delete('Semester_Model_SemesterWeek')
            ->where('year=?',$year)
            ->andwhere('semester=?',$semester);
            $q->execute();

            foreach($arr as $val) {
                if ($val) {
                    //$row = $semester_week->createRow();
                    $semesterWeek = new Semester_Model_SemesterWeek();
                    $semesterWeek->year= $year;
                    $semesterWeek->semester = $semester;
                    $semesterWeek->week_no = $i;
                    $semesterWeek->start_date = $val;
                    $semesterWeek->save();

                    $i++;
                }
            }
        }
        $this->_helper->Json('');
    }

    /**
     * 取得週次資料
     *
     * @return array
     */

    private function _getWeekData($data)
    {
        if (empty($data))
        return array();

        $d=explode("-",$data['opened_date']);

        $smt=mktime(0,0,0,$d[1],$d[2],$d[0]);
        $w_day=date("Y-m-d",$smt);
        $dd=getdate($smt);
        $wmt=$smt-($dd['wday']*86400);
        $i=1;
        do {
            $w_day=date("Y-m-d",$wmt);
            $weekData[$i]=$w_day;
            $wmt+=86400*7;
            $i++;
        }
        while ($w_day < $data['closed_date']);
        array_pop($weekData);
        $this->_weekData = $weekData;
        return $weekData;

    }

    /**
     * 週次設定
     * @param unknown_type $data
     * @return multitype:|Ambigous <number, multitype:>
     */
    private function _getWeekSetupData($data)
    {
        if (empty($data))
        return array();
        $q = Doctrine_Query::create()
        ->from('Semester_Model_SemesterWeek')
        ->where('year=?', $this->view->year)
        ->andwhere('semester=?', $this->view->semester);
        $res = $q->fetchArray();
        $arr = array();

        if (count($res) > 0) $this->view->setWeekFlag = 1;
        foreach($res as $val) {
            $k=array_search($val['start_date'],$this->_weekData);
            if ($k) $arr[$k]=0;
        }

        foreach ($this->_weekData as $k=>$v){
            if (!isset($arr[$k]))
            $arr[$k]=1;
        }

        return $arr;
    }
}
